#!/bin/bash
die() {
	echo "Die on $*"
	exit 1
}

# param: start_path detect_path result_path variable
detect_path(){
	start_path=$1
	detect_path=$2

	while true ; do
		if [ -e "$start_path/$detect_path" ]; then
			printf -v $4 $start_path/$3
			break
		elif [ "$start_path" == "/" -o "$start_path." == "." ]; then
			break
		else
			start_path=`dirname $start_path`
		fi
	done
}
detect_tools_path(){
	detect_path $1 tools/cmake tools J_TOOLS_PATH
	[ "$J_TOOLS_PATH." == "." ] && die failed to found tools path
}

detect_cmake_path_mac(){
	detect_tools_path $1
	if [ "$J_CMAKE_VERSION." == "."  ]; then 
		(type -p cmake > /dev/null  || die "Cmake not found") && J_CMAKE_PATH=`type -p cmake` 
	else
		J_CMAKE_PATH=$J_TOOLS_PATH/cmake/$J_CMAKE_VERSION/bin-macub/cmake
	fi
}

detect_cmake_path_linux(){
	detect_tools_path $1
	if [ "$J_CMAKE_VERSION." == "."  ]; then 
		(type -p cmake > /dev/null  || die "Cmake not found") && J_CMAKE_PATH=`type -p cmake` 
	else
		J_CMAKE_PATH=$J_TOOLS_PATH/cmake/$J_CMAKE_VERSION/bin-linux/cmake
	fi
}

